-- filebot.lua

-- By Tyrone, on 16/04/07
-- Keeps track of file shares

---- Variable Init -----
CurrentTransactions = {}
Shares = {}               -- Shares[share, detail]
TempName = {}
TempType = {}
TempMagnet = {}
TempDesc = {}
TempYear = {}
TempRip = {}
TempEp = {}
------------------------

-----------------------------------------------------------------------Table Structure for Shares Table:----------------------------------------------------------------------------
-- ID --       Name      --   Type   --  Magnet  --                      Description                                -- Year -- Rip Kind -- Artist/EpNumber -- Submitter -- Rating --
--  1 -- Charlotte's Web -- Movie    -- magnet:? -- A spider tries to save a pig's life by weaving words into a web -- 2006 -- DVDScr   -- nil             -- Aethereal -- 4.3    --
--  2 -- Stargate SG-1   -- TV       -- magnet:? -- Sam goes to an alternate reality where stargate is public       -- 2007 -- TVRip    -- S10E12          -- Aethereal -- 3.9    --
--  3 -- X&Y             -- Music    -- magnet:? -- Coldplay's 2005 Album                                           -- 2005 -- MP3      -- Coldplay        -- Aethereal -- 4.9    --
--  4 -- The Sims 2      -- Software -- magnet:? -- THIS-ISAC-DKEY-STOR-ED13-37LY                                   -- 2004 -- ISO      -- EA Games        -- Aethereal -- 3.7    --
--  5 -- Photoshop CS3   -- Software -- magnet:? -- THIS-ISAC-DKEY-STOR-ED13-37LY Mac OS X Version                  -- 2007 -- DMG      -- Adobe           -- Aethereal -- 3.5    --
--  6 -- 2001            -- Book     -- magnet:? -- An AI malfunctions on board a ship headed for Jupiter           -- 1967 -- PDF      -- A.C Clarke      -- Aethereal -- 2.6    --
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

---- Change These Variables ----
AdminsEmail = "voidboi@gmail.com"
--------------------------------

-------- STRINGS - LOCALISATION --------
HELLO1 =		"hi"
HELLO2 =		"hello"
HELLO3 =		"sup"
HELLO4 =		"yo"
NEW =			"new"
LATEST =		"latest"
BEST =			"best"
RATE =			"rate"
UPDATE =		"update"
LIST =			"list"
LISTALL =		"listall"
HELP =			"help"
BOT_DESCR = 	"PM me 'help' for details"
BOT_GREETING = 	string.format('Hello, what would you like to do today?  Acceptable commands are "hello", "new", "latest", "best", "rate", "update" and "list".  \nIf you would like help on any of these commands, just ask me help <command> (ignoring the "<>")')
BOT_CONFUSED =	string.format("I'm sorry, but I don't understand what you want.  Try asking me for help, by simply saying 'help'.")
BOT_WIZBEGIN =	string.format('\nADD A NEW FILE WIZARD\n\nWelcome to the Add A New File Wizard.  First, type in the NAME of the file you want to share.\nFor example, if I was to share a Stargate Episode, I would put\nStargate SG-1\n\nYou can cancel at any time by typing in Cancel')
BOT_CANCEL =	string.format('Your transaction has been cancelled.')

----------------------------------------

-- Main Function
-- No Parameters, No Result
-- Primary execution method; fires when script is !luaload-ed
function Main()
	VH:AddRobot("FileBot", 10, "PM me 'help' for details", "Bot", AdminsEmail, 0)
end

-- UnLoad Function
-- No Parameters, No Result
-- Final execution method; fires when script is !luaunload-ed
function UnLoad()
	VH:DelRobot("FileBot")
end

-- VH_OnParsedMsgPM Function
-- Parameter String from - User who sent the PM
-- Parameter String data - Message data contained in the PM
-- Parameter String to   - User who PM is addressed to
-- Result Integer        - 0 discards data; 1 ignores script
-- Method which triggers every time a private message is parsed.  Used to monitor for FileBot chat.
function VH_OnParsedMsgPM(from, data, to)
	if (to == "FileBot") then                    -- should be addressed to the filebot
		if (CurrentTransactions[from] == nil or CurrentTransactions[from] < 2) then
			data = string.lower(data)                -- case insensitive
			if (GetUserCommand(data) == 1) then
				SendPMToUser(string.format('Hello, what would you like to do today?  Acceptable commands are "hello", "new", "latest", "best", "rate", "update" and "list".  \nIf you would like help on any of these commands, just ask me help <command> (ignoring the "<>")'), from, "FileBot")
				CurrentTransactions[from] = 1
			elseif (GetUserCommand(data) == 2) then StartNewShare(from)
			elseif (GetUserCommand(data) == 3) then GetLatestShares(from)
			elseif (GetUserCommand(data) == 4) then GetBestShares(from)
			elseif (GetUserCommand(data) == 5) then SetRating(from, data)
			elseif (GetUserCommand(data) == 6) then StartUpdate(from)
			elseif (GetUserCommand(data) == 7) then GetList(from)
			elseif (GetUserCommand(data) == 8) then SendHelpToUser(from, string.sub(data, 6))
			else
				SendPMToUser("I'm sorry, but I don't understand what you want.  Try asking me for help, by simply saying 'help'.", from, "FileBot")
			end
		else
		UserSentSequencePM(from, data)
		end
		return 0
	end
	return 1
end

-- GetUserCommand Function
-- Parameter String input - Message data hopefully containing a bot instruction
-- Result Integer:

--User commands:
--1 = Start transaction ("hello")
--2 = Create a new share ("new")
--3 = Latest shares ("latest")
--4 = Highest rated ("best")
--5 = Rate a share ("rate")
--6 = Update a magnet ("update")
--7 = List all ("list")
--8 = Help ("help")
-- Converts a string into an Integer representing a command a user has given the FileBot.
function GetUserCommand(input)
	if (string.find(string.lower(input), "^hello")) then return 1
	elseif (string.find(string.lower(input), "^hi")) then return 1
	elseif (string.find(string.lower(input), "^sup")) then return 1
	elseif (string.find(string.lower(input), "^yo")) then return 1
	elseif (string.find(string.lower(input), "^new")) then return 2
	elseif (string.find(string.lower(input), "^latest")) then return 3
	elseif (string.find(string.lower(input), "^best")) then return 4
	elseif (string.find(string.lower(input), "^rate")) then return 5
	elseif (string.find(string.lower(input), "^update")) then return 6
	elseif (string.find(string.lower(input), "^list")) then return 7
	elseif (string.find(string.lower(input), "^listall")) then return 7
	elseif (string.find(string.lower(input), "^help")) then return 8
	else return 0
	end
end

-- SendMessageToHub Function
-- Parameter String data - Message to send to hub
-- Parameter String from - Owner of the message
-- Result Integer - Always returns 1
-- Sends a message to the Hub's main chat window.
function SendMessageToHub(data, from)
	result, err = VH:SendDataToAll("<"..from.."> "..data.."|",0,10)
	return 1
end

-- SendMessageToUser Function
-- Parameter String data - Message to send to a specific user
-- Parameter String nick - User to send message to
-- Parameter String from - Owner of the message
-- Result Integer - Always returns 1
-- Sends a message to the Hub's main chat window, that only the specified user can see.
function SendMessageToUser(data, nick, from)
	result, err = VH:SendDataToUser("<"..from.."> "..data.."|", nick)
	return 1
end

-- SendPMToUser Function
-- Parameter String data - Message to send to user
-- Parameter String from - Owner of the message
-- Result Integer - Always returns 1
-- Sends a message to a user that appears as a Private Message.
function SendPMToUser(message, to, from)
	result, err = VH:SendDataToUser("$To: "..to.." From: "..from.." $<"..from.."> "..message.."|", to)
	return 1
end

-- StartNewShare Function
-- Parameter String user - User who is adding new share
-- Puts the user into new state where they can procedurally add a new file into the database.
function StartNewShare(user)
	SendPMToUser(string.format('\nADD A NEW FILE WIZARD\n\nWelcome to the Add A New File Wizard.  First, type in the NAME of the file you want to share.\nFor example, if I was to share a Stargate Episode, I would put\nStargate SG-1\n\nYou can cancel at any time by typing in Cancel'), user, "FileBot")
	CurrentTransactions[user] = 2
end

-- GetLatestShares Function
-- Parameter String user - User who is requesting the list
-- Retrieves a list of the 5 latest additions to the database and PMs it to the requester.
function GetLatestShares(user)
	SendPMToUser("You typed 'latest' - this function isn't implemented yet :D", user, "FileBot")
end

-- GetBestShares Function
-- Parameter String user - User who is requesting the list
-- Retrieves a list of the 5 highest rated files in the database
-- Todo: Get Best Movie, Get Best Music etc
function GetBestShares(user)
	SendPMToUser("You typed 'best' - this function isn't implemented yet :D", user, "FileBot")
end

-- SetRating Function
-- Parameter String user - User who is rating content
-- Parameter String data - Text request to be parsed
-- Sets this user's rating of some content to a value.  Average is recalculated.
function SetRating(user, data)
	SendPMToUser("You typed 'rate' - this function isn't implemented yet :D", user, "FileBot")
end

-- StartUpdate Function
-- Parameter String user - User who is requesting the update
-- Allows changes to an already stored file in the database, such as new description or new magnet etc
function StartUpdate(user)
	SendPMToUser("You typed 'update' - this function isn't implemented yet :D", user, "FileBot")
end

-- GetList Function
-- Parameter String user - User who is requesting the file list
-- Prints out a list of every file in the list
-- Todo: Get Music, Get Movies etc
function GetList(user)
	SendPMToUser("You typed 'list' - this function isn't implemented yet :D", user, "FileBot")
end

-- SendHelpToUser Function
-- Parameter String user - User who is requesting help
-- Parameter Integer command - Command number user is requesting help for
-- Private Messages the user with detailed information on how to use the FileBot's commands.
function SendHelpToUser(user, command)
	if (command == "hello") then
		SendPMToUser(string.format('\nCommand Name: Hello \nBegins your transaction with the FileBot. \n\nSyntax:\nhello'), user, "FileBot")
	elseif (command == "new") then
		SendPMToUser(string.format('\nCommand Name: New \nBegins a step-by-step process to add a file to the system. \n\nSyntax:\nnew'), user, "FileBot")
	elseif (command == "latest") then
		SendPMToUser(string.format('\nCommand Name: Latest \nLists the 5 most recently added files to the system. \n\nSyntax:\nlatest'), user, "FileBot")
	elseif (command == "best") then
		SendPMToUser(string.format('\nCommand Name: Best \nLists the current top 5 highest rated files shared on the hub. \n\nSyntax:\nbest'), user, "FileBot")
	elseif (command == "rate") then
		SendPMToUser(string.format('\nCommand Name: Rate \nAdds a rating to a file currently stored in the system.  You can only rate a file once. \n\nSyntax:\nrate filenumber rating \nfilenumber - the unique number of the file share.  You can find it out through the list command. \nrating - number between 1 and 5 where 5 is great and 1 is rubbish.'), user, "FileBot")
	elseif (command == "update") then
		SendPMToUser(string.format('\nCommand Name: Update \nBegins a step-by-step process to change a file in the system. \n\nSyntax:\nupdate'), user, "FileBot")
	elseif (command == ("list")) then
		SendPMToUser(string.format('\nCommand Name: List \nLists all files currently tracked by the FileBot, and their unique number. \n\nSyntax:\nlist'), user, "FileBot")
	else
		SendPMToUser(string.format('\nValid commands are:\nHelp hello\nHelp new\nHelp latest\nHelp best\nHelp rate\nHelp update\nHelp list'), user, "FileBot")
	end
end

-- UserSentSequencePM Function
-- Parameter String user - User who is continuing sequence
-- Parameter String data - What they typed
-- If the user's current transaction state is saying they are involved in a transaction, this will fire
function UserSentSequencePM(user, data)
	if (string.lower(data) == "cancel") then
		TempName[user] = ""
		TempType[user] = ""
		TempMagnet[user] = ""
		TempDesc[user] = ""
		TempYear[user] = ""
		TempRip[user] = ""
		TempEp[user] = ""
		CurrentTransactions[user] = 1
		SendPMToUser("Your transaction has been cancelled."..string.format('\nHello, what would you like to do today?  Acceptable commands are "hello", "new", "latest", "best", "rate", "update" and "list".  \nIf you would like help on any of these commands, just ask me help <command> (ignoring the "<>")'), user, "FileBot")
	elseif (CurrentTransactions[user] == 2) then --This person just typed in the file's name
		TempName[user] = data            --This user's temporary name variable gets set
		CurrentTransactions[user] = CurrentTransactions[user] + 1
		SendPMToUser(string.format('Thank you.  The name you entered:\n')..data..string.format('\nhas been stored successfully.  Now, what type of file are you trying to add?  Valid types are:\nMovie, TV, Music, Software and Book'), user, "FileBot")
	elseif (CurrentTransactions[user] == 3) then --This person just typed in the file's type
		data = string.lower(data)
		if (data == "movie" or data == "tv" or data == "music" or data == "software" or data == "book") then --it is a valid type
			SendPMToUser(string.format('Thank you.  The type you entered:\n')..data..string.format('\nhas been stored successfully.  Now, please paste the MAGNET link to the file here.  If you cannot do magnet links or do not know what they are simply type in "nil" to skip this step.'), user, "FileBot")
			TempType[user] = data
			CurrentTransactions[user] = CurrentTransactions[user] + 1
		else
			SendPMToUser(string.format('Sorry, but what you typed was not a valid file type.  Try: Movie, TV, Music, Software or Book.'), user, "FileBot")
		end
	elseif (CurrentTransactions[user] == 4) then --This person just typed in the file's magnet, or typed in nil'
		if (string.sub(data, 1, 8) == "magnet:?") then
			SendPMToUser(string.format('Thank you.  The magnet you entered:\n')..data..string.format('\nhas been stored successfully.  Now, please add a description of your file here.  For example, "Sam goes to an alternate reality where stargate is public"'), user, "FileBot")
			TempDesc[user] = data
			CurrentTransactions[user] = CurrentTransactions[user] + 1
		elseif (string.lower(data) == "nil") then
			SendPMToUser(string.format('You have skipped the MAGNET step.  Now, please add a description of your file here.  For example, "Sam goes to an alternate reality where stargate is public"'), user, "FileBot")
			TempDesc[user] = nil
			CurrentTransactions[user] = CurrentTransactions[user] + 1
		else
			SendPMToUser(string.format('Sorry, you did not appear to enter a valid magnet link.  Please ensure the link begins with magnet:?    --- If you wish to skip this step, simply type in "nil".'), user, "FileBot")
		end
	elseif (CurrentTransactions[user] == 5) then --This person just typed in the description
		TempDesc[user] = data
		CurrentTransactions[user] = CurrentTransactions[user] + 1
		SendPMToUser(string.format('Thank you.  The description you entered:\n')..data..string.format('\nhas been stored successfully.  Now, please add a year of your file here.  For example, "2007"'), user, "FileBot")
	elseif (CurrentTransactions[user] == 6) then --This person just typed in the year
		TempYear[user] = data
		CurrentTransactions[user] = CurrentTransactions[user] + 1
		SendPMToUser(string.format('Thank you.  The year you entered:\n')..data..string.format('\nhas been stored successfully.  Now, please add a rip kind of your file here.  For example, "TVRip".  You can generally find this somewhere in the file name.  Look for a tag like DVDScr, TVRip, TS, Cam etc.  If in doubt, just put the file extension here, like MP3, or AVI.'), user, "FileBot")
	elseif (CurrentTransactions[user] == 7) then --This person just typed in the riptype
		TempRip[user] = data
		if (TempType[user] == "movie") then
			CurrentTransactions[user] = 1
			SendPMToUser(string.format('Thank you.  The rip type you entered:\n')..data..string.format('\nhas been stored successfully.').."  You're all done!", user, "FileBot")
		else
			CurrentTransactions[user] = CurrentTransactions[user] + 1
			if (TempType[user] == "tv") then 
				FieldName = "Episode Number"
				Example = "S10E12"
			else
				FieldName = "Artist"
				Example = "Coldplay"
			end
			SendPMToUser(string.format('Thank you.  The rip type you entered:\n')..data..string.format('\nhas been stored successfully.  Now, please add an')..FieldName.." of your file here.  For example, '"..Example.."'.", user, "FileBot")
		end
	elseif (CurrentTransactions[user] == 8) then --This person just typed in the artist/epnumber
		CurrentTransactions[user] = 1
		TempEp[user] = data
		SendPMToUser(string.format('Thank you.  What you entered:\n')..data..string.format('\nhas been stored successfully.').."  You're all done!", user, "FileBot")
	end
end